package com.dacool.fragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.dacool.activity.BaseActivity;
import com.dacool.app.sale.R;
import com.dacool.dialog.BasePickerDialog.PickerDialogDelegate;
import com.dacool.dialog.ChooseAddressDialog;
import com.dacool.http.BaseRequest;
import com.dacool.http.BaseRequest.ResponseHandler;
import com.dacool.http.CancelOrderRequest;
import com.dacool.http.GetOrderInfoRequest;
import com.dacool.http.UpdateOrderRequest;
import com.dacool.http.WapPayRequest;
import com.dacool.model.CartItem;
import com.dacool.model.DCAddress;
import com.dacool.model.DaCoolTransactionBill;
import com.dacool.model.DacoolProduct;
import com.dacool.util.ViewUtils;
import com.dacool.view.holder.CartItemCell;

public class OrderFragmentStep2 extends BaseFragment implements OnClickListener {

	private DaCoolTransactionBill bill;
	private LinearLayout itemContainer;
	private ViewHolder userInfoContainer;
	private ViewHolder payMethodContainer;

	private TextView totalPriceLabel;
	private TextView deliverFeeLabel;
	private TextView discountLabel;
	private TextView discountedPriceLabel;
	private Button confirmButton;
	private Button cancelButton;

	private TextView orderNumLabel;
	private TextView orderStatusLabel;

	private double totalPrice = 0;
	private int selectedPayMethod = 0;
	private ChooseAddressDialog addressDialog;
	private DCAddress address = null;

	private class ViewHolder {
		private View container;
		private TextView configurableTextView1;
		private TextView configurableTextView2;
		private EditText textInput;
	}

	public void setBill(DaCoolTransactionBill bill) {
		this.bill = bill;
	}

	// @Override
	// protected boolean showDefaultLeftButton() {
	// // TODO Auto-generated method stub
	// return true;
	// }

	@Override
	protected boolean showDefaultSecondLeftButton() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	protected int myLayoutID() {
		// TODO Auto-generated method stub
		return R.layout.frag_orderinfo;
	}

	@Override
	protected View myView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
		itemContainer = ViewUtils.findViewById(view, R.id.itemContainer);

		userInfoContainer = new ViewHolder();
		userInfoContainer.container = ViewUtils.findViewById(view,
				R.id.userInfoContainer);
		userInfoContainer.configurableTextView1 = ViewUtils.findViewById(view,
				R.id.userInfo_name);
		userInfoContainer.configurableTextView2 = ViewUtils.findViewById(view,
				R.id.userInfo_address);
		userInfoContainer.container.setOnClickListener(this);

		payMethodContainer = new ViewHolder();
		payMethodContainer.container = ViewUtils.findViewById(view,
				R.id.purchMethodContainer);
		payMethodContainer.configurableTextView1 = ViewUtils.findViewById(view,
				R.id.payInfo_method);

		payMethodContainer.container.setOnClickListener(this);

		totalPriceLabel = ViewUtils.findViewById(view, R.id.priceLabel);
		deliverFeeLabel = ViewUtils.findViewById(view, R.id.deliverFeeLabel);
		discountedPriceLabel = ViewUtils.findViewById(view,
				R.id.calculatedPriceLabel);
		discountLabel = ViewUtils.findViewById(view, R.id.coolbdiscountLabel);
		confirmButton = ViewUtils.findViewById(view, R.id.goPurchaseButton);
		cancelButton = ViewUtils.findViewById(view, R.id.cancelOrderButton);

		orderNumLabel = ViewUtils.findViewById(view, R.id.orderNumLabel);
		orderStatusLabel = ViewUtils.findViewById(view, R.id.orderStatusLabel);
		cancelButton.setOnClickListener(this);

		confirmButton.setOnClickListener(this);

		updateInfo();
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		if (v == confirmButton) {
			this.showProgressDialog(null, false);
			new WapPayRequest().setOrderId(bill.billId).setPayMethodId(1)
					.setHandler(new ResponseHandler() {

						@Override
						public void handleResponse(BaseRequest request,
								int statusCode, String errorMsg, String response) {
							OrderFragmentStep2.this.dismissProgressDialog();
							// TODO Auto-generated method stub
//							Log.d("test", "statusCode:" + statusCode
//									+ ",response " + response);
							if (statusCode == 301 || statusCode == 302) {
								Intent intent = new Intent(getActivity(),
										BaseActivity.class);
								intent.putExtra(
										BaseActivity.IntentKeyFragmentClass,
										WebViewFragment.class);
								intent.putExtra("url", response);
								intent.putExtra(
										BaseActivity.IntentKeyFullScreen, true);
								intent.putExtra(BaseActivity.IntentKeyHasTitle,
										true);
								getActivity().startActivity(intent);
								// WebViewFragment fragment = new
								// WebViewFragment();
								// fragment.setUrl(response);
								// getContainerActivity().addFragment(fragment);
							}
						}
					}).start();
		} else if (v == cancelButton) {
			this.showProgressDialog(null, false);
			new CancelOrderRequest().setOrderId(bill.billId)
					.setHandler(new ResponseHandler() {

						@Override
						public void handleResponse(BaseRequest request,
								int statusCode, String errorMsg, String response) {
							OrderFragmentStep2.this.dismissProgressDialog();
							if (statusCode != 200) {
								ViewUtils.runInMainThread(new Runnable() {

									@Override
									public void run() {

										Toast.makeText(getActivity(), "取消失败",
												Toast.LENGTH_LONG).show();

									}
								});
								return;
							} else {
								boolean success = false;
								String errmsg = null;
								try {
									JSONObject obj = new JSONObject(response);
									success = obj.optBoolean("success", false);
									errmsg = obj.optString("msg", null);
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								if (success) {
									getContainerActivity().handleBackButton();
								} else {
									String msg = errmsg != null ? errmsg
											: "取消失败";
									ViewUtils.showToast(msg, Toast.LENGTH_LONG);
								}
							}
						}
					}).start();
		} else if (v == userInfoContainer.container) {
			if ("dead".equals(bill.statusLabel)
					|| "finish".equals(bill.statusLabel)) {
				return;
			} else {
				if (!"0".equals(bill.payStatus)) {
					return;
				}
			}
			if (addressDialog == null)
				addressDialog = new ChooseAddressDialog(getActivity());
			addressDialog.setDelegate(new PickerDialogDelegate() {

				@Override
				public void selectedItemAtIndex(int index) {
					// TODO Auto-generated method stub
					address = addressDialog.getAddresses().get(index);
					editInfo();
				}

				@Override
				public void didCancel() {
					// TODO Auto-generated method stub

				}
			}).show();
		}
	}

	private void editInfo() {
		if (address != null)
			new UpdateOrderRequest().setOrderId(bill.billId)
					.setAddressId(address.id).setMarkText("")
					.setPayMethod(bill.payMethod)
					.setHandler(new ResponseHandler() {

						@Override
						public void handleResponse(BaseRequest request,
								int statusCode, String errorMsg, String response) {
							// TODO Auto-generated method stub
							loadOrderInfo();
						}
					}).start();
	}

	private void updateInfo() {
		totalPrice = 0;
		if (this.bill != null) {
			itemContainer.removeAllViews();
			for (CartItem item : this.bill.items) {
				View itemView = CartItemCell.createFromInflator(LayoutInflater
						.from(getActivity()));
				CartItemCell cell = (CartItemCell) itemView.getTag();
				if (item.getProduct().getIconUrl() != null
						&& item.getProduct().getIconUrl().length() > 0) {
					ViewUtils.bmUtils.display(cell.iconView, item.getProduct()
							.getIconUrl());
				} else
					cell.iconView.setImageResource(R.drawable.bannerimg);
				cell.titleLabel.setText(item.getProduct().getName());
				cell.priceLabel.setText(String.format("%d x %.2f",
						item.getAmount(), item.getProduct().getPrice()));
				totalPrice += item.getAmount() * item.getProduct().getPrice();
				int index = itemContainer.getChildCount() - 1;
				itemView.setTag(null);
				itemView.setBackgroundResource(R.drawable.graybg);
				LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,
						LayoutParams.WRAP_CONTENT);
				itemContainer.addView(itemView, index, lp);

			}
		}

		totalPriceLabel.setText(String.format("¥ %.2f", bill.sumPrice));
		discountedPriceLabel.setText(String.format("¥ %.2f", bill.totalPrice));

		orderNumLabel.setText((bill.billId < 0) ? "" : "" + bill.billId);
		userInfoContainer.configurableTextView1.setText(String.format("%s %s",
				bill.deliverMan, bill.deliverMobile));
		userInfoContainer.configurableTextView2.setText(String.format("%s %s",
				bill.deliverArea, bill.deliverAddr));
		payMethodContainer.configurableTextView1.setText(bill.payMethod);
		orderStatusLabel.setText(bill.getOrderStatusString());

		confirmButton.setVisibility(View.VISIBLE);
		cancelButton.setVisibility(View.VISIBLE);
		if ("dead".equals(bill.statusLabel)
				|| "finish".equals(bill.statusLabel)) {
			confirmButton.setVisibility(View.INVISIBLE);
			cancelButton.setVisibility(View.INVISIBLE);
		} else {
			if (!"0".equals(bill.payStatus)) {
				confirmButton.setVisibility(View.INVISIBLE);
			}
		}
	}

	private void loadOrderInfo() {
		this.showProgressDialog(null, false);
		new GetOrderInfoRequest().setOrderID(bill.billId)
				.setHandler(new ResponseHandler() {

					/**
					 * {id:”3342”, "orderNo": "10070532", "status":"客户作废"
					 * Goods:{
					 * [goodsId:”123”,name:”牛奶1L”,price:”10.9”,img:”10/11/
					 * 123.jpg”],
					 * [goodsId:”123”,name:”牛奶”,price:”10.9”,img:”10/11
					 * /123.jpg”]}, totalPrice:”商品总价21.8”, deliverFee:”运费10”,
					 * dacoolMoney :”库币抵扣5”,sumPrice:”合计6.8”,deliverAddr:”收货地址”,
					 * deliverTime :”配送时间：一周内全天可送打”, payMethod:”支付方式”,
					 * invoice:”发票信息” }
					 */

					// XXX todo
					@Override
					public void handleResponse(BaseRequest request,
							int statusCode, String errorMsg, String response) {
						// TODO Auto-generated method stub
						OrderFragmentStep2.this.dismissProgressDialog();
						if (statusCode != 200) {
							ViewUtils.runInMainThread(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									Toast.makeText(getActivity(), "获取详情失败",
											Toast.LENGTH_LONG).show();
								}
							});
							return;
						} else {
							try {
								JSONObject object = new JSONObject(response);
								JSONObject data = object.getJSONObject("data");
								JSONArray goods = data.getJSONArray("items");
								bill.billId = data.getLong("orderId");
								// bill.orderNo = object.getString("orderNo");
								bill.statusLabel = data.getString("status");
								bill.priceLabel = data.getString("costItem");
								// bill.deliveryFee = "0";
								bill.payMethod = data.getString("payment");
								bill.deliverAddr = data.getString("shipAddr");
								bill.deliverMan = data.getString("shipName");
								bill.deliverMobile = data
										.getString("shipMobile");
								bill.shipStatus = data.getString("shipStatus");
								bill.payStatus = data.getString("payStatus");
								bill.deliverArea = data.getString("shipArea");
								bill.items.clear();
								for (int i = 0; i < goods.length(); i++) {
									JSONObject obj = goods.getJSONObject(i);
									DacoolProduct product = new DacoolProduct();
									product.setName(obj.getString("name"));
									product.setIconUrl(obj
											.getString("thumbnail"));
									product.setPrice(obj.getDouble("price"));
									product.setId(obj.getString("goodsId"));
									CartItem item = new CartItem();
									item.setAmount(obj.getInt("nums"));
									item.setProduct(product);
									bill.items.add(item);
								}
								ViewUtils.runInMainThread(new Runnable() {

									@Override
									public void run() {
										// TODO Auto-generated method stub
										updateInfo();
									}
								});
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
				}).start();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		loadOrderInfo();
	}

}
